package Demo80;

import java.util.*;
import java.util.function.BiConsumer;

/**
 * 前 K 个高频单
 * https://leetcode.cn/problems/top-k-frequent-words/
 */
class PRE {
    String str;
    Integer count;
    public PRE(String str, Integer count) {
        this.str = str;
        this.count = count;
    }
}
class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>();
        // 遍历数组,统计单词出现的次数
        for(String word : words) {
            map.put(word,map.getOrDefault(word,0) + 1);
        }
        // 创建小根堆
        PriorityQueue<PRE> queue = new PriorityQueue<>(new Comparator<PRE>() {
            @Override
            public int compare(PRE o1, PRE o2) {
                if(o1.count != o2.count) {
                    return o1.count - o2.count;
                }
                return o2.str.compareTo(o1.str);
            }
        });
        // 遍历map
        for (Map.Entry<String,Integer> e : map.entrySet()) {
            queue.offer(new PRE(e.getKey(),e.getValue()));
            if (queue.size() > k) queue.poll();
        }
//        map.forEach(new BiConsumer<String, Integer>() {
//            @Override
//            public void accept(String s, Integer integer) {
//                queue.offer(new PRE(s,integer));
//                if (queue.size() > k) queue.poll();
//            }
//        });
        // 遍历堆
        List<String> ret = new ArrayList<>();
        while(!queue.isEmpty()) {
            ret.add(queue.poll().str);
        }
        Collections.reverse(ret);
        return ret;
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] str = new String[] {"i","love","leetcode","i","love","coding"};
        List<String> list = solution.topKFrequent(str, 2);
        System.out.println(Arrays.toString(list.toArray()));
    }
}